import utils from "./util";
import storage from "../storage/storage.js";
import config from "../config/config.js";

export default function request(obj={}){
	let token=storage.getItem('token');
	// const headers = {
	// 	'Content-Type': 'application/x-www-form-urlencoded',
	// 	token: token
	// };
	
	return new Promise((resolve,reject)=>{
		if(obj.token!==undefined && obj.token == true){
			obj.data=obj.data||{};
			obj.data.token=token;
		};
		if(obj.loading!==undefined && obj.loading == true){
			uni.showLoading({
				title:obj.msg||'正在加载',
				mask:true,
			})
		};
		uni[obj.upload?'uploadFile':'request']({
			...obj,
			url:config.baseUrl + (obj.url||''),
			method:obj.method||'POST',
			// header: headers,
			header:obj.header?Object.assign({},config.header,obj.header):config.header,
			[obj.upload?'formData':'data']:obj.data||{},
			success(res) {
				uni.hideLoading();
				if (typeof res.data === 'string') {
					try {
						res.data = JSON.parse(res.data);
					} catch (e) {
					}
				}
				if(res.data.status == 2) {
					uni.showModal({
						title: '登录提示',
						content: '身份已过期，请重新登录后再来操作！',
						success:ress => {
							if (ress.confirm) {
								uni.redirectTo({
									url:'/pages/login/src/main'
								})
							}
						}
					})
				}
				// console.log(obj.url, obj.data)
				resolve(res.data)
			},
			fail(err){
				uni.hideLoading();
				reject(err);
			}
			
		})
	})
}